import React, { useState, useEffect, useCallback } from 'react';
import { 
  Button, Card, Divider, Input, notification, 
  Spin, Space, Row, Col, Typography, message, TreeSelect 
} from 'antd';
import { LoadingOutlined, SaveOutlined, SyncOutlined } from '@ant-design/icons';
import useStore from '../../../components/useStore';
import { useLocation } from 'react-router-dom';
import request from '../../../untils/request';

const { Title, Text } = Typography;
const { TreeNode } = TreeSelect;

// 所有样式定义在一个对象中
const styles = {
  container: {
    height: '94%',
    backgroundColor: '#F1F1F1',
    position: 'absolute',
    top: '4vh',
    right: '1%',
    overflow: 'hidden',
    color: '#333',
    transition: 'width 0.3s ease'
  },
  containerCollapsed: {
    width: '94%'
  },
  containerExpanded: {
    width: '84%'
  },
  card: {
    margin: '24px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
    borderRadius: '8px',
    overflow: 'hidden'
  },
  title: {
    marginBottom: '16px',
    color: '#1890ff'
  },
  formRow: {
    marginBottom: '16px'
  },
  errorText: {
    fontSize: '12px',
    marginTop: '-8px',
    color: '#ff4d4f'
  },
  treeSelectContainer: {
    margin: '24px auto',
    padding: '16px',
    backgroundColor: '#f9f9f9',
    borderRadius: '4px',
    maxWidth: '900px',
    width: '100%'
  },
  menuItem: {
    display: 'flex',
    flexDirection: 'column'
  },
  menuDescription: {
    fontSize: '12px',
    color: '#888',
    marginTop: '4px'
  },
  helpTextContainer: {
    marginTop: '24px',
    paddingTop: '16px',
    borderTop: '1px dashed #e8e8e8'
  },
  helpText: {
    fontSize: '12px',
    lineHeight: '1.6',
    color: '#666'
  },
  loadingContainer: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    height: '300px',
    color: '#666'
  },
  operationButtons: {
    margin: '0 8px'
  },
  treeSelectWrapper: {
    width: '100%',
    marginTop: '16px'
  },
  buttonGroup: {
    marginTop: '16px',
    textAlign: 'right'
  }
};

const EditRoleForm = () => {
  const { collapsed } = useStore();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [updatingPermissions, setUpdatingPermissions] = useState(false);
  const [role, setRole] = useState({
    role_name: "",
    ok_menus: [],      // 该角色可查看的菜单
    no_menus: [],      // 该角色无法查看的菜单
    all_menus: [],     // 所有菜单
    selectedKeys: [],  // 选中的菜单key（有权限的）
    id: 0,             // 角色id
  });
  const [formError, setFormError] = useState('');
  const [tempSelectedKeys, setTempSelectedKeys] = useState([]); // 临时存储选中的key，用于取消确认
  
  const location = useLocation();

  // 递归构建树形节点
  const renderTreeNodes = useCallback((data) => {
    return data.map((item) => {
      if (item.children && item.children.length > 0) {
        return (
          <TreeNode title={item.title} key={item.key} value={item.value}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  }, []);

  // 提取所有选中的节点ID
  const getAllSelectedKeys = useCallback((menus) => {
    let keys = [];
    
    const traverse = (menuItems) => {
      menuItems.forEach(item => {
        keys.push(item.key);
        if (item.children && item.children.length > 0) {
          traverse(item.children);
        }
      });
    };
    
    traverse(menus);
    return keys;
  }, []);

  // 获取角色信息
  const fetchRoleInfo = useCallback((id) => {
    setLoading(true);
    request("/admin/role/getInfoById", {
      method: 'POST',
      body: { id }
    }).then(data => {
      // 提取有权限的菜单ID
      const selectedKeys = getAllSelectedKeys(data.ok_menus);
      
      setRole(prev => ({
        ...prev,
        id: data.id,
        role_name: data.role_name,
        ok_menus: data.ok_menus,
        no_menus: data.no_menus,
        all_menus: data.all_menus,
        selectedKeys
      }));
      
      // 同步临时选中的key
      setTempSelectedKeys(selectedKeys);
      setFormError('');
    }).catch(error => {
      message.error('获取角色信息失败，请刷新页面重试');
      console.error('Error fetching role info:', error);
    }).finally(() => {
      setLoading(false);
    });
  }, [getAllSelectedKeys]);

  // 初始化加载角色信息
  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);
    const id = parseInt(queryParams.get('id'));
    if (id) {
      fetchRoleInfo(id);
    } else {
      message.error('未找到角色ID参数');
      setLoading(false);
    }
  }, [fetchRoleInfo, location.search]);

  // 处理角色名称变更
  const handleRoleNameChange = useCallback((e) => {
    const value = e.target.value;
    setRole(prev => ({ ...prev, role_name: value }));
    
    // 实时验证
    if (value && !/^[\u4e00-\u9fa5]{2,20}$/.test(value)) {
      setFormError('角色名称必须为2-20个汉字');
    } else {
      setFormError('');
    }
  }, []);

  // 保存角色名称
  const handleSaveRoleName = useCallback(() => {
    if (!/^[\u4e00-\u9fa5]{2,20}$/.test(role.role_name)) {
      notification.error({
        message: '验证失败',
        description: '角色名称必须为2-20个汉字',
        placement: 'topRight'
      });
      return;
    }

    setSaving(true);
    const req = {
      role_name: role.role_name,
      id: role.id
    };

    request("/admin/role/updateRoleName", {
      method: 'POST',
      body: req
    }).then(data => {
      if (data.code === 200) {
        notification.success({
          message: '操作成功',
          description: data.msg,
          placement: 'topRight'
        });
      } else {
        notification.error({
          message: '操作失败',
          description: data.msg || '更新角色名称失败',
          placement: 'topRight'
        });
      }
    }).catch(error => {
      notification.error({
        message: '网络错误',
        description: '保存角色名称时发生错误',
        placement: 'topRight'
      });
      console.error('Error saving role name:', error);
    }).finally(() => {
      setSaving(false);
    });
  }, [role]);

  // 处理树形选择器变更
  const handleTreeSelectChange = useCallback((selectedKeys) => {
    setTempSelectedKeys(selectedKeys);
  }, []);

  // 确认更新权限
  const confirmPermissionChange = useCallback(() => {
    // 如果没有变更，不执行操作
    if (tempSelectedKeys.join(',') === role.selectedKeys.join(',')) {
      notification.info({
        message: '提示',
        description: '未修改任何权限设置',
        placement: 'topRight'
      });
      return;
    }

    setUpdatingPermissions(true);
    
    request("/admin/role/updateUserMenuPermission", {
      method: 'POST',
      body: {
        role_id: role.id,
        new_menus_id: tempSelectedKeys.map(key => parseInt(key)) // 转换为数字类型
      }
    }).then(data => {
      if (data.code === 200) {
        // 刷新角色信息
        fetchRoleInfo(role.id);
        notification.success({
          message: '操作成功',
          description: data.msg || '权限更新成功',
          placement: 'topRight'
        });
      } else {
        notification.error({
          message: '操作失败',
          description: data.msg || '更新权限失败',
          placement: 'topRight'
        });
      }
    }).catch(error => {
      notification.error({
        message: '网络错误',
        description: '更新权限时发生错误',
        placement: 'topRight'
      });
      console.error('Error updating permissions:', error);
    }).finally(() => {
      setUpdatingPermissions(false);
    });
  }, [role.id, tempSelectedKeys, role.selectedKeys, fetchRoleInfo]);

  // 取消变更
  const cancelPermissionChange = useCallback(() => {
    setTempSelectedKeys(role.selectedKeys);
  }, [role.selectedKeys]);

  if (loading) {
    return (
      <div style={styles.loadingContainer}>
        <Spin indicator={<LoadingOutlined spin size="large" />} />
        <p>加载角色信息中...</p>
      </div>
    );
  }

  return (
    <div 
      style={{
        ...styles.container,
        ...(collapsed ? styles.containerCollapsed : styles.containerExpanded)
      }}
    >
      <Card style={styles.card}>
        <Title level={4} style={styles.title}>编辑角色</Title>
        <Divider orientation="left" plain>基本信息</Divider>
        
        <Row gutter={[16, 16]} style={styles.formRow}>
          <Col xs={24} sm={16} md={12} lg={10}>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <Text strong>角色名称</Text>
              <Input
                value={role.role_name}
                onChange={handleRoleNameChange}
                maxLength={20}
                showCount
                placeholder="请输入2-20个汉字的角色名称"
                status={formError ? 'error' : undefined}
                tooltip={formError}
              />
              {formError && (
                <Text type="error" style={styles.errorText}>{formError}</Text>
              )}
              <Button 
                type="primary" 
                danger 
                onClick={handleSaveRoleName} 
                loading={saving}
                icon={<SaveOutlined />}
              >
                保存角色名称
              </Button>
            </Space>
          </Col>
        </Row>

        <Divider orientation="left" plain style={{ marginTop: 24 }}>菜单权限设置</Divider>
        
        {/* 树形选择组件区域 */}
        <div style={styles.treeSelectContainer}>
          <Text strong>请选择该角色可访问的菜单（支持多选）：</Text>
          <div style={styles.treeSelectWrapper}>
            <TreeSelect
              showSearch
              style={{ width: '100%' }}
              value={tempSelectedKeys}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择菜单权限"
              allowClear
              multiple
              treeDefaultExpandAll
              onChange={handleTreeSelectChange}
              loading={updatingPermissions}
            >
              {renderTreeNodes(role.all_menus)}
            </TreeSelect>
          </div>
          
          <div style={styles.buttonGroup}>
            <Space size="middle">
              <Button 
                onClick={cancelPermissionChange}
                disabled={updatingPermissions}
              >
                取消
              </Button>
              <Button 
                type="primary" 
                onClick={confirmPermissionChange}
                loading={updatingPermissions}
                icon={<SyncOutlined spin={updatingPermissions} />}
              >
                保存权限设置
              </Button>
            </Space>
          </div>
        </div>

        <div style={styles.helpTextContainer}>
          <Text type="secondary" style={styles.helpText}>
            提示：角色名称不得与已存在的名称重复，所有输入内容均有长度限制。
            菜单权限采用树形结构展示，勾选父菜单会自动勾选所有子菜单。
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default EditRoleForm;
